<?php
require_once("Password.php");
class Merchant_Service_Customer
{

	public function __construct(){

	}

	 

	/**
	*初始化customer Account
	*
	*
	*/
	private function _initAccount($customerRow){
		$customrModelObj = new Merchant_Model_Customer();
		$customrBalanceModel = new Merchant_Model_CustomerBalance();

		$customrModelObj->getAdapter()->beginTransaction();
		try{
			    //添加客户记录

			   $customerRow['customer_id'] = $this->genCustomerId();
			   $customrId = $customrModelObj->add($customerRow);

			   $timeNow = date('Y-m-d H:i:s');
			   $customrBalance = array('customer_id'=>$customrId,
			   							'currency_code'=>'RMB',
										'cb_add_time'=>$timeNow,
										'cb_last_update'=>$timeNow);
									
				//生成客户Balance
			   $customrBalanceModel->add($customrBalance);
			   
			   //发送激活码邮件
			  // $CustomerEmailActivateObj = new Merchant_Service_CustomerEmailActivate($customerRow['customer_id'],$customerRow['customer_email'],12);
			   //$CustomerEmailActivateObj->makeKey()->sendMail();
			   $customrModelObj->update(array('customer_activate_code'=>'123','customer_status'=>1),$customerRow['customer_id']);
				
			   //记录日志
			   $this->writeLog($customerRow,$customrId,2);
			   $customrModelObj->getAdapter()->commit();
			   // $customerRow["customer_id"] = $customrId;
			   $this->setLoginInfo(true,$this->get($customrId));//注册成功直接登录
			   return true;
		} catch (Exception $e) {
					echo $e->getTraceAsString();
					echo $e->getMessage();
					$customrModelObj->getAdapter()->rollBack();
					$logger =  Zend_Registry::get('log');
					$logger->info(date('Y-m-d H:i:s').': '.$e->getMessage()." \n");
					return false;
		}
	}
	private function getNextPre($pre){
    	$notArr =array('L','O','I');
        $pre = Chr(Ord(strtoupper($prx))+1);

        if(in_array($pre,$notArr)){
            $this->getNextPre($prx);
		}
        return $pre;
    }

	//生成客户ID
	private function genCustomerId(){		
		$pre = 'A';
		$dig = '0001';
		$objConfig = new Default_Model_Config();
		$customerRow = $objConfig->getByValue('CURRENCY_CUSTOMER_ID');
		if(!empty($customerRow)){
                $pre = substr($customerRow['config_value'],0,1);
				$dig = substr($customerRow['config_value'],-4);
        }else{				 
                $customerRow = array(
                    'config_attribute' => 'CURRENCY_CUSTOMER_ID',
                    'config_value' => $pre.$dig,                    
                    'config_description' =>'当前生成客户ID值',
					'config_create_time' => date('Y-m-d H:i:s'),                    
                    'config_last_update' => date('Y-m-d H:i:s')
                );
                $customerRow['config_id'] = $objConfig->add($customerRow);
        }
		
		
		
		
		
		$userCode = $pre.str_pad($dig,4,'0',STR_PAD_LEFT);
		
		
		$dig += 1;
		
		if($dig>=1000){
			$pre = $this->getNextPre($prx);
			$dig = '0001';
		} 
		$dig = str_pad($dig,4,'0',STR_PAD_LEFT);
		
		$update =array(
			'config_value' => $pre.$dig
		);
		$objConfig->update($update,$customerRow['config_id']);
		 
       return   $userCode;
	
	}
	
	
	public function get($customerId = null){
		$customer = Merchant_Model_Customer::getInstance()->getDbTable()->find(self::getCustomerId($customerId))->current();
		if($customer instanceof Zend_Db_Table_Row){
			return $customer->toArray();
		}
		return false;
	}

	/**
	* 用户注册业务
	* @author hjyang
	* @param array $row
	* @return array|boolean success return boolean,false return array
	*/
	public function register($row){
		$error = $this->validateRegisterInfo($row);
		if(!empty($error)){
			return $error;
		}
		if(isset($row['rePassword'])) unset($row['rePassword']);
		$row['customer_password'] = $this->encryptionPassword($row['customer_password']);
		 //初始化帐号
		return $this->_initAccount($row);
	}



	/**
	* 用户注册数据验证
	* @author hjyang
	* @param array $row
	* @return
	*/
	public function validateRegisterInfo($row){
        $lang=Common_Service_Get::getClass('validator');
		$error = array();

		if("" == $row['customer_email']){
			$error[] = "Email ".$lang['required'];
		}else if(!preg_match("/^[0-9a-zA-Z]+(?:[\_\-][a-z0-9\-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\.[a-zA-Z]+$/i",$row['customer_email'])){
			$error[] = "Email ".$lang['content_email'];
		}else if($this->existsEmail($row['customer_email'])){
			$error[] = "Email ".$lang['exists'];
		}

		if(trim($row['customer_password']) != $row['rePassword']){
			$error[] = $lang['passwords'];
		}
		return $error;
	}
	
	/**
	* 用户取回密码时邮箱及验证码验证
	* @param array $row
	* @return
	*/
	public function validateForGetPwd($row){
		$error = array();

		if("" == $row['email']){
			$error[] = "Email can not be empty!";
		}else if(!preg_match("/^[0-9a-zA-Z]+(?:[\_\-][a-z0-9\-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\.[a-zA-Z]+$/i",$row['email'])){
			$error[] = "Email format is not correct!";
		}else if(!self::existsEmail($row['email'])){
			$error[] = "Email not exists!";
		}
		
		$verifyCode = new Default_Service_Verifycode();
		$verifyCode->set_sess_name('UserVerifyCode');
		if(strlen($row['verifyCode']) != 5){
			$error[] = "The captcha does not match!";
		}else if( !$verifyCode->is_true($row['verifyCode']) ){
			$error[] = "The captcha does not match!";
		}
		return $error;
	}
	
	/**
	* 用户取回密码时邮箱及验证码验证
	* @param array $row
	* @return
	*/
	public function validateModifyPwd($row){
		$error = array();
		
		$oldPassword =  $row['oldPassword']; 
		$password = $row['password']; 
		$rePassword = $row['rePassword']; 

        $customerService = new Merchant_Service_Customer();
		$customerInfo = $customerService->getLoginInfo()->customer;

		if(!$password || !$rePassword){
            $error[] = '请输入新密码';
        }
        
		if(!Default_Service_Password::comparePassword($oldPassword, $customerInfo['customer_password'])){
            $error[] = '原密码错误';
        }
		if($password != $rePassword){
            $error[] = '新密码两次输入不一致';
        }
		if(strlen($password) < 6){
            $error[] = '密码长度不能小于 6 .';
        }
		if($oldPassword == $password){
            $error[] = '新密码不能与原密码相同';
        }
		
		return $error;
	}

	/**
	* 判断邮箱是否已经存在
	* @param $string email
	* @return boolean|array
	*/
	public function existsEmail($email){
		$customrModelObj = new Merchant_Model_Customer();
		$customer = $customrModelObj->existsEmail($email);
		if($customer){
			return $customer->toArray();
		}
		return false;
	}
	/**
	* 设置用户登录信息
	* @param boolean $isLogin
	* @param array $infos
	* @return void
	*/
	public function setLoginInfo($isLogin,$customer = null){
		$sessionUser = new Zend_Session_Namespace("customer");
		$sessionUser->isLogin = $isLogin;
		if($isLogin){
			/*
				customer对应数据表customer的数据
			*/
			$sessionUser->customer = $customer;
			$sessionUser->lang = "1";//临时处理
		}else{
			if(isset($sessionUser->infos)) unset($sessionUser->infos);
		}
	}

	/**
	* 取得用户登录信息
	* @return Zend_Session_Namespace
	*/
	public function getLoginInfo(){
		$sessionUser = new Zend_Session_Namespace("customer");
		return $sessionUser;
	}

	/**
	* 用户登出
	* @return void
	*/
	public function logout(){
		$this->setLoginInfo(false);
	}

	/**
	* 获得本对象实例
	* @return Merchant_Service_Customer；
	*/
	public static function getInstance(){
		return new Merchant_Service_Customer();
	}

	/**
	* 用户登录
	* @param string email
	* @param string password
	* @return boolean
	*/
	public function login($email,$password ,$param = false){
       
		$customrModelObj = new Merchant_Model_Customer();
		// $customer = $customrModelObj->getByEmailAndPassword($email,$this->encryptionPassword($password));
		// if($customer instanceof Zend_Db_Table_Row_Abstract){//存在该用户,登录成功
			// $customer = $customer->toArray();
			// $this->setLoginInfo(true,$customer);
			// $this->writeLog($customer,$customer['customer_id'],0);
			// return true;
		// }
		$customer = $customrModelObj->getByValue($email,"customer_id");
		$customer2 = $customrModelObj->getByValue($email,"customer_email");
		if(is_array($customer) && !empty($customer)){
			if (Password::comparePassword($password, $customer['customer_password']) || $param) {
				$this->setLoginInfo(true,$customer);
				$this->writeLog($customer,$customer['customer_id'],0);
				return true;
			}
		}
		if(is_array($customer2) && !empty($customer2)){
			if (Password::comparePassword($password, $customer2['customer_password']) || $param) {
				$this->setLoginInfo(true,$customer2);
				$this->writeLog($customer2,$customer2['customer_id'],0);
				return true;
			}
		}
		return false;
        
	}

	/**
	* 加密
	* @param string password
	* @return string
	*/
	public function encryptionPassword($password){
		return Password::getHash($password);
	}

	/**
	* 用户账号日志记录
	* $param array $row
	* $param int $customerId
	* $param int $type
	* @return void
	*/
	public function writeLog($row,$customerId,$type){
		$note = "";
		foreach($row as $key => $value){
				$note .= $key.":".$value.";";
		}
		$dbTable = Merchant_Model_CustomerHistory::getInstance()->getDbTable();
		$log = array(
			"ch_type" => $type,
			"customer_id" => $customerId,
			"ch_note" => $note,
			"ch_date" => date("Y-m-d H:i:s"),
		);
		$dbTable->insert($log);
	}

	/**
	* 查询当前客户id
	* @param int|null customerId
	* @return int
	*/
	public function getCustomerId($customerId = null){
		if($customerId == null){
			$loginInfo = self::getLoginInfo();
			$customerId = $loginInfo->customer['customer_id'];
		}
		return $customerId;
	}

	/**
	* 更新客户信息
	* @param array $row
	* @param int|null customerId
	* @return
	*/

	public function update($row,$customerId=null){
		$customrModelObj = new Merchant_Model_Customer();
		$customer = &$this->getLoginInfo()->customer;
		if(isset($row["customer_firstname"])) $customer['customer_firstname'] = $row["customer_firstname"];
		if(isset($row["customer_lastname"])) $customer['customer_lastname'] = $row["customer_lastname"];
		if(isset($row["customer_telephone"])) $customer['customer_telephone'] = $row["customer_telephone"];
		if(isset($row["return_package_proccess"])) $customer['return_package_proccess'] = $row["return_package_proccess"];
		return $customrModelObj->update($row,$this->getCustomerId($customerId));
	}
	
	/**
	*  通过条件更新指定数据
	* @param array $row
	* @param array $cond
	* @return
	*/
	public function updateByVal($row,$field,$val){
		$Obj = new Merchant_Model_Customer();
		return $Obj->updateByVal($row,$field,$val);
	}

	public function validateCustomerInfo($row){
		$error = array();
		foreach($row as $key => $value){
			if($value == ""){
				$error[$key] = "This field is required";
			}
		}
		return $error;
	}
	
	 
	
	public static function checkRegister(){
		$serviceObj = new Merchant_Service_Customer();
		$customer = $serviceObj->getLoginInfo()->customer;
		if(!isset($customer["reg_step"]) || $customer["reg_step"] != 3){
			return '1';
		}elseif($customer['customer_status'] == '2'){
		
			return '2';
		}
		return false;
	}
	    
    public function customerActivate($customer_id,$customer_activate_code){
        $obj = new Merchant_Model_Customer();
        if($row=$obj->getByCustoemrIdAndActivateCode($customer_id,$customer_activate_code)){
            if($obj->update(array('customer_status'=>1),$customer_id) && $this->login($customer_id,'',true)){            
               return true;
            }
        }
        return false;
    }
	
	public function validateCustomer($task,$modify_email=''){
		$msg = '';
		$customrModelObj = new Merchant_Model_Customer();
		$customerServiceObj = new Merchant_Service_Customer();
		$customer = $customerServiceObj->getLoginInfo()->customer;
		$CustomerEmailActivateObj = new Merchant_Service_CustomerEmailActivate($customer['customer_id'],$modify_email,12);
		if('resend' == $task){
			$CustomerEmailActivateObj->makeKey()->sendMail();
			$customrModelObj->update(array('customer_activate_code'=>$CustomerEmailActivateObj->code),$customer['customer_id']);
            $msg = 'The validation email has been resent.';
        }elseif('modify' == $task){
			if($this->existsEmail($modify_email)){
				$msg = 'E-mail address you entered already exists, Please change another one.';
			}else{
				$CustomerEmailActivateObj->makeKey()->sendMail();
				$customrModelObj->update(array('customer_activate_code'=>$CustomerEmailActivateObj->code,'customer_email'=>$modify_email),$customer['customer_id']);
				$msg = 'Your email address has been updated and a new validation email has been sent. Please disregard any previous validation emails as they will no longer work.';
			}
        }
		return $msg;
	}
}